<template>
  <div class="container view-container">
    <div :contentScrollbar="true" class="search">
      <div class="searchFormRef">
        <div class="item">
          <div class="label2">生成日期：</div>
          <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="item">
          <div class="label">通道列表:</div>
          <el-select v-model="channelValue" placeholder="" size="large">
            <el-option v-for="item in channels" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div class="btn">
        <el-button class="item" type="primary" @click="searchData">查询</el-button>
        <el-button class="item" type="primary" @click="resetSearch">重置</el-button>
      </div>
    </div>
    <div class="tableList">
      <div class="btn">
        <div class="left"></div>
        <el-button style="margin: 5px 60px" type="primary" @click="recordAndEdit()"> 录制与编辑 </el-button>
      </div>
      <div class="tablecontent">
        <BaseTable v-bind="tableProps" v-loading="loading"  :paginationData="paginationData" :tableData="tableData" ref="BaseTableRef">
         
        </BaseTable>
      </div>
      <div class="footer">
        <div class="BasePagination">
          <BasePagination :paginationData="paginationData" @paginationChange="searchData" />
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onActivated } from 'vue';
import router from '@renderer/src/router';
import BasePagination from '@/components/BasePagination/index.vue';
import BaseTable from '@/components/BaseTable/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getVideoInfoQuery,
  getVideoInfoListCount,
  deleteVideo,
  getVideoMarkListByVedioId,
  getRightMarkListByVideoId,
  getChannelFromDb,
} from '@renderer/src/utils/ipc';
import { userSystemStore } from '@/store';
const channelValue = ref(0);
const systemStore = userSystemStore();
const paginationData = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

const value1 = ref();
const loading = ref(false);
const BaseTableRef = ref(null);

let channels = reactive([{ value: 0, label: '全部' }]);

let savePath = '';

//正在导入的进程数据
let currentExport = [
  {
    row: null,
    cancelFuntion: () => {}, //用户取消下载
  },
];

const tableProps = reactive({
  tableColumns: [
    {
      type: 'index',
      width: 150,
      label: '序号',
    },
    {
      prop: 'video_name',
      label: '视频名称',
    },
    {
      prop: 'video_duration',
      label: '视频时长(S)',
      width: 150,
    },
    {
      prop: 'file_size',
      label: '视频大小(MB)',
      width: 150,
    },
    {
      prop: 'create_time',
      label: '生成时间',
    },
    {
      prop: 'channel',
      label: '通道',
      render: ({ row, item }) => { return transShowData({row, item, prop: 'channel'}) }
    },
    {
      prop: 'download_status',
      label: '下载状态',
      type: 'progress',
    },
    {
      label: '操作',
      width: 250,
      fixed: 'right',
      operaterList: [
        {
          name: '删除',
          operater: (item) => {
            deleteRecord(item.row);
          },
        },
        {
          name: '下载',
          unname: '取消下载',
          type: 'progress',
          prop: 'download_status',
          operater: (item) => {
            downLoadFile(item);
          },
        },
      ],
    },
  ],
});

const transShowData = (scope) => {
  if(scope.row.channel == 1) {
    return "摄像头1"
  } else if(scope.row.channel == 2) {
    return "摄像头2"
  } else if(scope.row.channel == 3) {
    return "摄像头3"
  } else if(scope.row.channel == 4) {
    return "摄像头4"
  } else if(scope.row.channel == 5) {
    return "摄像头5"
  } else if(scope.row.channel == 6) {
    return "摄像头6"
  } else if(scope.row.channel == 7) {
    return "摄像头7"
  } else {
    return scope.row.channel
  }

};

const tableData = reactive([
  {
    id: '1',
    video_name: '',
    video_duration: '3',
    file_size: 1024,
    start_time: '',
    end_time: '',
    channel: '',
    status: '0',
    download_status: 0,
    save_path: '',
    create_time: '',
    create_user: '',
  },
]);

onActivated(async () => {
  channels.length = 0
  let temp = systemStore.getChannels();
  channels.push({ value: 0, label: '全部' });
  temp.forEach((element) => {
    channels.push({ value: element.label, label: element.label.toString() });
  });
  console.log(channels)
  searchData();
});

//查询数据
const searchData = async () => {
  try {
    tableData.length = 0;
    loading.value = true;
    let startT = value1.value ? value1.value[0] + ' 00:00:00' : '';
    let endT = value1.value ? value1.value[1] + ' 23:59:59' : '';
    console.log(channels)
    let queryParams = {
      videoName: '',
      startTime: startT,
      endTime: endT,
      channel: channelValue.value === 0 ? '' : channelValue.value,
      page: paginationData.pageSize,
      current: paginationData.pageSize * (paginationData.pageNum - 1),
    };
    console.log(queryParams)
    let rest = await getVideoInfoQuery(queryParams);
    rest.map((item) => tableData.push(item));
    let res = await getVideoInfoListCount(queryParams); //获取总记录数
    paginationData.total = res.count;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
};

//下载
const downLoadFile = async (item) => {
  if (currentExport.length > 0 && currentExport[0].row == null) {
    currentExport.length = 0;
  }
  if (item.row.download_status == 0 || item.row.download_status >= 100) {
    setTimeout(async () => {
      await exportData(item.row);
    }, 100);
  } else if (item.row.download_status > 0 && item.row.download_status < 100) {
    const itemStop = currentExport.find((itemIng) => {
      if (itemIng.row === item.row) {
        return itemIng;
      }
    });
    if (itemStop) {
      let index = currentExport.indexOf(itemStop);
      if (index !== -1) {
        item.row.download_status = 0;
        await currentExport[index].cancelFuntion();
        currentExport.splice(index, 1);
      }
    }
  }
};

const exportData = async (row) => {
  //选择文件夹
  if (savePath == '') {
    savePath = await window.api.openDirectory();
    savePath = savePath ? savePath : '';
  }
  if (savePath !== '') {
    row.download_status = 0;
    let source = row.save_path + `\\${row.video_name}`;
    const cancelFuntion = window.api.copyFileWithProgress(
      source,
      savePath + `\\${row.video_name}`,
      (transferred, progress) => {
        let current = parseInt((100.0 * (transferred / progress)).toString());
        if (row.download_status < current) {
          row.download_status = current;
          if (row.download_status >= 100) {
            const itemFinish = currentExport.find((itemIng) => {
              if (itemIng.row === row) return itemIng;
            });
            if (itemFinish) {
              let index = currentExport.indexOf(itemFinish);
              currentExport.splice(index, 1);
              savePath = '';
              ElMessage.success('下载完成');
            } else {
              row.download_status = 0;
            }
          }
        }
      },
    );
    currentExport.push({ row: row, cancelFuntion });
  } else {
    ElMessage.error('请选择保存路径');
  }
};

const deleteRecord = (row) => {
  ElMessageBox.confirm('是否确定删除当前数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(async () => {
      await deleteItem(row);
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};

const deleteItem = async (row) => {
  //查找是否存在标注信息
  let resRealMarkInfoList = await getVideoMarkListByVedioId({ id: row.id });
  let resTimeMarkInfoList = await getRightMarkListByVideoId({ id: row.id });
  if (resRealMarkInfoList.length > 0 || resTimeMarkInfoList > 0) {
    ElMessageBox.confirm('该视频已有标注信息 是否删除，该操作不可逆?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    })
      .then(async () => {
        await deleteDD(row);
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  } else {
    await deleteDD(row);
  }
};

const deleteDD = async (row) => {
  await deleteVideo({
    id: row.id,
    status: '1',
  });
  const item = tableData.find((item) => {
    if (row.id == item.id) {
      return item;
    }
  });
  if (item) {
    let index = tableData.indexOf(item);
    console.log(index);
    if (index != -1) {
      tableData.splice(index, 1);
    }
    console.log(tableData);
  }
  ElMessage({
    type: 'success',
    message: '删除成功',
  });
};

//录制与编辑
const recordAndEdit = async () => {
  void router.push({ path: '/videoRecordAndEdit/recordAndEdit' });
};

//重置
const resetSearch = async () => {
  value1.value = null;
  channelValue.value = null;
  searchData();
};
</script>
<style lang="less" scoped>
:deep(.el-table thead th) {
  font-weight: 500;
  font-size: 16px;
  color: #020f1b;
  font-style: normal;
}
.container {
  display: flex;
  flex-direction: column;
  padding: 6px;
  height: 100%;
  width: 100%;
  min-width: 650px;
  width: auto;
  .search {
    height: 100px;
    background-color: rgb(240, 242, 245);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .searchFormRef {
      display: flex;
      flex-direction: row;
      height: 50px;
      justify-content: center;
      align-items: center;
      .item {
        display: flex;
        flex-direction: row;
        justify-content: start;
        align-items: center;
        margin-left: 10px;
        .label {
          font-weight: 500;
          font-size: 16px;
          color: #020f1b;
          font-style: normal;
          margin-left: 10px;
          width: 150px;
        }
      }
    }
    .btn {
      flex: 1;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      .item {
        width: 100px;
      }
    }
  }
  .tableList {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    overflow: hidden;
    height: 100%;
    .btn {
      display: flex;
      justify-content: space-between;
      min-width: 580px;
      width: 100%;
      align-items: flex-end;
      border-bottom: solid rgb(240, 242, 245) 1px;
      .left {
        flex: 1;
      }
      .el-button {
        width: 120px;
      }
    }
    .tablecontent {
      flex: 1;
      width: 100%;
      position: relative; // table的直接父元素加position属性
      :deep(.el-table) {
        // table 加position属性
        position: absolute;
      }
    }
    .footer {
      height: 80px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
      .BasePagination {
        // left: 50%;
        height: 100%;
      }
    }
  }
}
</style>
